﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using BP.OA.PublicPlan;
using BP.En;
using BP.DA;
using BP.Web;
using BP.Sys;
using BP.Tools;
using System.Data;

namespace CCOA.App.PublicPlan
{
    public partial class PlanMain : System.Web.UI.Page
    {
        /// <summary>
        /// 获取传入参数
        /// </summary>
        /// <param name="param">参数名</param>
        /// <returns></returns>
        public string getUTF8ToString(string param)
        {
            return HttpUtility.UrlDecode(Request[param], System.Text.Encoding.UTF8);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string method = string.Empty;
            //返回值
            string s_responsetext = string.Empty;
            if (string.IsNullOrEmpty(Request["method"]))
                return;

            method = Request["method"].ToString();
            switch (method)
            {
                case "loadcurloginuserno"://获取当前登录人
                    s_responsetext = LoadCurLoginUserNo();
                    break;
                case "getplanmainapps"://获取计划列表
                    s_responsetext = GetPlanCatalogs();
                    break;
                case "getplanstates":
                    s_responsetext = GetPlanStates();
                    break;
                case "plannodemanage"://计划管理
                    s_responsetext = PlanNodeManage();
                    break;
                case "getplancatalogtick"://获取反馈内容列表
                    s_responsetext = GetPlanCatalogTicks();
                    break;
                case "createplancatalogtick"://新建记录
                    s_responsetext = CreatePlanCatalogTick();
                    break;
                case "backpreplan"://返回上一层
                    s_responsetext = BackPrePlan();
                    break;
                case "deleteplanstage"://删除反馈情况
                    s_responsetext = DeletePlanStage();
                    break;
                case "sartupplan"://启动计划
                    s_responsetext = SartUpPlan();
                    break;
                case "shutdownplan"://结束计划
                    s_responsetext = ShutDownPlan();
                    break;
                case "updaterootname"://修改根节点名称
                    s_responsetext = UpdateRootName();
                    break;
                case "getparentplanpartake"://获取父级负责人
                    s_responsetext = GetParentPlanPartake();
                    break;
            }
            if (string.IsNullOrEmpty(s_responsetext))
                s_responsetext = "";
            //组装ajax字符串格式,返回调用客户端
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "text/html";
            Response.Expires = 0;
            Response.Write(s_responsetext);
            Response.End();
        }

        /// <summary>
        /// 获取当前登录人编号
        /// </summary>
        /// <returns></returns>
        private string LoadCurLoginUserNo()
        {
            return WebUser.No;
        }

        /// <summary>
        /// 获取上级计划负责人
        /// </summary>
        /// <returns></returns>
        private string GetParentPlanPartake()
        {
            string planNo = getUTF8ToString("nodeNo");
            PlanCatalog planCatalog = new PlanCatalog();
            planCatalog.RetrieveByAttr(PlanCatalogAttr.No, planNo);
            //参与人
            string planPartake = planCatalog.PlanPartake + ",";
            //负责人、参与人、新建人、admin
            if (planCatalog.PersonCharge == WebUser.No || planPartake.Contains(WebUser.No + ",")
                || planCatalog.FK_Emp == WebUser.No || WebUser.No == "admin")
                return planNo;
            //查找父级
            return GetParentPlanRight(planCatalog.ParentNo);
        }
        //迭代
        private string GetParentPlanRight(string planNo)
        {
            PlanCatalog planCatalog = new PlanCatalog();
            planCatalog.RetrieveByAttr(PlanCatalogAttr.No, planNo);
            //不是根节点
            if(planCatalog.ParentNo != "0")
            {
                //参与人
                string planPartake = planCatalog.PlanPartake + ",";
                //负责人、参与人、新建人、admin
                if (planCatalog.PersonCharge == WebUser.No || planPartake.Contains(WebUser.No + ",") || planCatalog.FK_Emp == WebUser.No)
                {
                    return "true";
                }
                return GetParentPlanRight(planCatalog.ParentNo);
            }
            return "false";
        }

        /// <summary>
        /// 修改根节点名称
        /// </summary>
        /// <returns></returns>
        private string UpdateRootName()
        {
            string nodeNo = getUTF8ToString("nodeNo");
            string rootName = getUTF8ToString("rootName");
            PlanCatalog planCata = new PlanCatalog();
            planCata.RetrieveByAttr(PlanCatalogAttr.No, nodeNo);
            planCata.Name = rootName;
            planCata.Update();
            return "true";
        }

        /// <summary>
        /// 启动计划
        /// </summary>
        /// <returns></returns>
        private string SartUpPlan()
        {
            try
            {
                string nodeNo = getUTF8ToString("nodeNo");
                PlanCatalog planCata = new PlanCatalog();
                planCata.RetrieveByAttr(PlanCatalogAttr.No, nodeNo);
                //如果不是负责人不允许启动
                if (WebUser.No != "admin" && planCata.PersonCharge != WebUser.No)
                {
                    return "notpersoncharge";
                }
                //如果父计划还未启动，则不能启动
                PlanCatalog parentPlanCata = new PlanCatalog();
                parentPlanCata.RetrieveByAttr(PlanCatalogAttr.No, planCata.ParentNo);
                if (parentPlanCata.ParentNo != "0" && parentPlanCata.PlanState == PlanState.Normal)
                {
                    return "no";
                }
                planCata.StartUpDate = BP.DA.DataType.CurrentData;
                planCata.PlanState = PlanState.SartUp;
                planCata.Update();
                return "true";
            }
            catch (Exception ex)
            {
            }
            return "false";
        }

        /// <summary>
        /// 结束计划
        /// </summary>
        /// <returns></returns>
        private string ShutDownPlan()
        {
            try
            {
                string nodeNo = getUTF8ToString("nodeNo");
                PlanCatalog planCata = new PlanCatalog();
                planCata.RetrieveByAttr(PlanCatalogAttr.No, nodeNo);
                //如果不是负责人不允许结束
                if (WebUser.No != "admin" && planCata.PersonCharge != WebUser.No)
                {
                    return "notpersoncharge";
                }
                //子计划没结束完，不允许结束
                PlanCatalogs childPlanCatas = new PlanCatalogs();
                childPlanCatas.RetrieveByAttr(PlanCatalogAttr.ParentNo, nodeNo);
                foreach (PlanCatalog item in childPlanCatas)
                {
                    if (item.PlanState == PlanState.EndOf)
                        continue;
                    return "no";
                }
                planCata.RelEndDate = BP.DA.DataType.CurrentData;
                planCata.PlanState = PlanState.EndOf;
                planCata.Update();
                return "true";
            }
            catch (Exception ex)
            {
            }
            return "false";
        }

        /// <summary>
        /// 获取计划列表
        /// </summary>
        /// <returns></returns>
        private string GetPlanCatalogs()
        {
            string ParentNo = getUTF8ToString("ParentNo");
            string TreeNo = getUTF8ToString("TreeNo");
            string showCatalog = getUTF8ToString("showCatalog");
            //看记录是否存在
            PlanCatalogs planApps = new PlanCatalogs();
            QueryObject obj = new QueryObject(planApps);
            obj.AddWhere(PlanCatalogAttr.FK_Emp, "");
            obj.addOr();
            obj.AddWhere(PlanCatalogAttr.PersonCharge, WebUser.No);
            int RowCount = obj.GetCount();
            //查询
            obj.DoQuery();

            if (planApps == null || planApps.Count == 0)
            {
                string startDate = BP.DA.DataType.CurrentData;
                string endDate = String.Format("{0:yyyy-MM-dd}", DateTime.Now.AddMonths(1));
                PlanCatalog planCatalog = new PlanCatalog();
                planCatalog.No = "99";
                planCatalog.Name = "计划管理";
                planCatalog.ICON = "icon-plan-root";
                planCatalog.ParentNo = "0";
                planCatalog.Insert();

                PlanCatalog subPlan = planCatalog.DoCreateSubNode() as PlanCatalog;
                subPlan.Name = "计划一";
                subPlan.FK_Emp = WebUser.No;
                subPlan.FK_Dept = WebUser.FK_Dept;
                subPlan.PersonCharge = WebUser.No;
                subPlan.PCModel = PCModel.PlanModel;
                subPlan.ICON = "icon-plan-0";
                subPlan.StartDate = startDate;
                subPlan.EndDate = endDate;
                subPlan.Update();

                subPlan = subPlan.DoCreateSubNode() as PlanCatalog;
                subPlan.Name = "子计划";
                subPlan.FK_Emp = WebUser.No;
                subPlan.FK_Dept = WebUser.FK_Dept;
                subPlan.PersonCharge = WebUser.No;
                subPlan.PCModel = PCModel.PlanModel;
                subPlan.ICON = "icon-plan-0";
                subPlan.StartDate = startDate;
                subPlan.EndDate = endDate;
                subPlan.Update();

                subPlan = planCatalog.DoCreateSubNode() as PlanCatalog;
                subPlan.Name = "计划二";
                subPlan.FK_Emp = WebUser.No;
                subPlan.FK_Dept = WebUser.FK_Dept;
                subPlan.PersonCharge = WebUser.No;
                subPlan.PCModel = PCModel.PlanModel;
                subPlan.ICON = "icon-plan-0";
                subPlan.StartDate = startDate;
                subPlan.EndDate = endDate;
                subPlan.Update();

                subPlan = subPlan.DoCreateSubNode() as PlanCatalog;
                subPlan.Name = "子计划";
                subPlan.FK_Emp = WebUser.No;
                subPlan.FK_Dept = WebUser.FK_Dept;
                subPlan.PersonCharge = WebUser.No;
                subPlan.PCModel = PCModel.PlanModel;
                subPlan.ICON = "icon-plan-0";
                subPlan.StartDate = startDate;
                subPlan.EndDate = endDate;
                subPlan.Update();
            }
            //重新查询
            string sql = "select a.*,b.Name FK_DeptText,c.Name PersonChargeText from OA_PlanCatalog a left join Port_Dept b on a.FK_Dept=b.No left join Port_Emp c on c.No=a.PersonCharge";
            sql += " where 1=1";
            if (!string.IsNullOrEmpty(TreeNo))
            {
                sql += " and a.TreeNo like '" + TreeNo + "%'";
            }
            else if (!string.IsNullOrEmpty(ParentNo))
            {
                PlanCatalog planCatalog = new PlanCatalog();
                planCatalog.RetrieveByAttr(PlanCatalogAttr.No, ParentNo);
                if (!string.IsNullOrEmpty(planCatalog.No))
                {
                    sql += " and a.TreeNo like '" + planCatalog.No + "%'";
                    ParentNo = planCatalog.ParentNo;
                }
                else
                {
                    ParentNo = "0";
                }
            }
            else
            {
                ParentNo = "0";
            }

            //如果不要求显示阶段
            if (!string.IsNullOrEmpty(showCatalog) && showCatalog.ToLower() == "false")
            {
                sql += " and a.PCModel=0";
            }
            sql += " ORDER BY Idx";

            DataTable dt = DBAccess.RunSQLReturnTable(sql);
            string strMenus = "";// BP.GPM.Utility.CommonDbOperator.GetGridTreeDataString(dt, "ParentNo", "No", ParentNo, true);

            if (strMenus.Length > 2)
                strMenus = strMenus.Remove(strMenus.Length - 2, 2);
            return strMenus;
        }

        /// <summary>
        /// 返回上一层
        /// </summary>
        /// <returns></returns>
        private string BackPrePlan()
        {
            string nodeNo = getUTF8ToString("nodeNo");
            PlanCatalog catalog = new PlanCatalog();
            catalog.RetrieveByAttr(PlanCatalogAttr.No, nodeNo);
            if (catalog == null || string.IsNullOrEmpty(catalog.Name))
            {
                return "{ParentNo:'0',TreeNo:''}";
            }
            return "{ParentNo:'" + catalog.ParentNo + "',TreeNo:'" + catalog.No + "'}";
        }

        /// <summary>
        /// 计划管理
        /// </summary>
        /// <returns></returns>
        private string PlanNodeManage()
        {
            string nodeNo = getUTF8ToString("nodeNo");
            string dowhat = getUTF8ToString("dowhat");
            string returnVal = "notpersoncharge";
            PlanCatalog planCata = new PlanCatalog(nodeNo);
            //如果是根节点,任何人都可以添加
            if (planCata.ParentNo == "0")
                planCata.PersonCharge = WebUser.No;
            //负责人或参与人\admin或新建人
            if (planCata.PersonCharge == WebUser.No || planCata.FK_Emp == WebUser.No || WebUser.No == "admin"
                || (!string.IsNullOrEmpty(planCata.PlanPartake) && planCata.PlanPartake.Split(',').Contains(WebUser.No)))
            {
                returnVal = planCata.No;
                string startDate =  BP.DA.DataType.CurrentData;
                string endDate = String.Format("{0:yyyy-MM-dd}", BP.OA.Main.CurDateTime.AddMonths(1));
                switch (dowhat.ToLower())
                {
                    case "sample"://新增同级节点                    
                        nodeNo = planCata.DoCreateSameLevelNode().No;
                        //新节点赋值
                        planCata = new PlanCatalog(nodeNo);
                        planCata.Name = "子计划" + nodeNo;
                        planCata.FK_Emp = WebUser.No;
                        planCata.FK_Dept = WebUser.FK_Dept;
                        planCata.PersonCharge = WebUser.No;
                        planCata.PCModel = PCModel.PlanModel;
                        planCata.ICON = "icon-plan-0";
                        planCata.StartDate = startDate;
                        planCata.EndDate = endDate;
                        planCata.Update();
                        returnVal = nodeNo;
                        break;
                    case "children"://新增子节点
                        nodeNo = planCata.DoCreateSubNode().No;
                        //新节点赋值
                        planCata = new PlanCatalog(nodeNo);
                        planCata.Name = "子计划" + nodeNo;
                        planCata.FK_Emp = WebUser.No;
                        planCata.FK_Dept = WebUser.FK_Dept;
                        planCata.PersonCharge = WebUser.No;
                        planCata.PCModel = PCModel.PlanModel;
                        planCata.ICON = "icon-plan-0";
                        planCata.StartDate = startDate;
                        planCata.EndDate = endDate;
                        planCata.Update();
                        returnVal = nodeNo;
                        break;
                    case "children_stage"://添加阶段
                        nodeNo = planCata.DoCreateSubNode().No;
                        //新节点赋值
                        planCata = new PlanCatalog(nodeNo);
                        planCata.Name = "阶段" + nodeNo;
                        planCata.FK_Emp = WebUser.No;
                        planCata.FK_Dept = WebUser.FK_Dept;
                        planCata.PersonCharge = WebUser.No;
                        planCata.PCModel = PCModel.StageModel;
                        planCata.ICON = "icon-plan-1";
                        planCata.StartDate = startDate;
                        planCata.EndDate = endDate;
                        planCata.Update();
                        returnVal = nodeNo;
                        break;
                    case "doup"://上移
                        planCata.DoUp();
                        break;
                    case "dodown"://下移
                        planCata.DoDown();
                        break;
                    case "delete"://删除
                        //含有子级不允许删除
                        PlanCatalogs planCatas = new PlanCatalogs();
                        planCatas.RetrieveByAttr(PlanCatalogAttr.ParentNo, planCata.No);
                        if (planCatas != null && planCatas.Count > 0)
                        {
                            return "havechild";
                        }
                        //负责人，新建人和admin可以删除
                        returnVal = "notpersoncharge";
                        if (planCata.PersonCharge == WebUser.No || planCata.FK_Emp == WebUser.No || WebUser.No == "admin")
                        {
                            returnVal = planCata.No;
                            if (planCata.PlanState == PlanState.SartUp)//已经结束不允许删除
                            {
                                returnVal = "isstartup";
                            }
                            else if (planCata.PlanState == PlanState.EndOf)//已启动不允许删除
                            {
                                returnVal = "isend";
                            }
                            else
                            {
                                planCata.Delete();
                            }
                        }
                        break;
                }
            }

            //返回
            return returnVal;
        }

        /// <summary>
        /// 新建计划反馈记录
        /// </summary>
        /// <returns></returns>
        private string CreatePlanCatalogTick()
        {
            string catalogNo = getUTF8ToString("catalogNo");
            PlanStageContent stageContent = new PlanStageContent();
            stageContent.FK_Emp = WebUser.No;
            stageContent.Name = WebUser.Name;
            stageContent.FK_PlanStageContent = catalogNo;
            stageContent.StartDate = BP.OA.Main.TransDateTimeShort(BP.DA.DataType.CurrentData);
            stageContent.EndDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");
            stageContent.Insert();
            return stageContent.No;
        }
        /// <summary>
        /// 删除反馈情况
        /// </summary>
        /// <returns></returns>
        private string DeletePlanStage()
        {
            string stageNo = getUTF8ToString("stageNo");
            PlanStageContent stageContent = new PlanStageContent();
            int i = stageContent.Delete(PlanStageContentAttr.No, stageNo);
            if (i > 0)
                return "true";
            return "false";
        }

        /// <summary>
        /// 获取计划反馈内容列表
        /// </summary>
        /// <returns></returns>
        private string GetPlanCatalogTicks()
        {
            //当前页
            string pageNumber = getUTF8ToString("pageNumber");
            int iPageNumber = string.IsNullOrEmpty(pageNumber) ? 1 : Convert.ToInt32(pageNumber);
            //每页多少行
            string pageSize = getUTF8ToString("pageSize");
            int iPageSize = string.IsNullOrEmpty(pageSize) ? 9999 : Convert.ToInt32(pageSize);
            //总行数
            int RowCount = 0;
            string catalogNo = getUTF8ToString("catalogNo");
            string isTick = getUTF8ToString("isTick");
            PlanStageContents planStageContents = new PlanStageContents();
            QueryObject obj = new QueryObject(planStageContents);
            obj.AddWhere(PlanStageContentAttr.FK_PlanStageContent, catalogNo);
            //参与人只获取自己的反馈内容
            if (isTick == "1")
            {
                obj.addAnd();
                obj.AddWhere(PlanStageContentAttr.FK_Emp, WebUser.No);
            }
            //获取总行数
            RowCount = obj.GetCount();
            //排序
            obj.addOrderByDesc(PlanStageContentAttr.No);
            //查询
            obj.DoQuery(PlanStageContentAttr.No, iPageSize, iPageNumber);

            return Entitis2Json.ConvertEntitis2GridJsonOnlyData(planStageContents, RowCount);
        }

        /// <summary>
        /// 获取计划状态
        /// </summary>
        /// <returns></returns>
        private string GetPlanStates()
        {
            SysEnums sysenumus = new SysEnums();
            sysenumus.RetrieveByAttr(SysEnumAttr.EnumKey, PlanCatalogAttr.PlanState);
            return Entitis2Json.ConvertEntities2ListJson(sysenumus);
        }
    }
}